<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .list {
            display: flex;
            text-align: center;
            width: 300px;
            height: 300px;
            background-color: pink;
            justify-content: space-evenly;
            flex-direction: column;
            flex-wrap: wrap;
        }
    </style>
</head>

<body>
    <div class="list">

    </div>
    <button class="prev">上一页</button>
    <button class="next">下一页</button>
</body>

</html>
<script>
    var page = 1
    //保存当前页码

    //将对象格式转为查询字符串格式
    function objToSearchString(obj) {
        var str = ''
        //遍历对象，将对象obj的每个属性名和属性值拼接为key=value&的格式
        for (var key in obj) {
            str += `${key}=${obj[key]}&`
        }
        //返回拼接好的字符串 key=value&key=value&key=value&key=vlaue
        return str.slice(0, str.length - 1)
    }
    function ajax(method, url, params, cb) {
        //1.创建请求对象
        var xhr = new XMLHttpRequest()
        //2.配置请求对象
        xhr.open(method, url + "?" + objToSearchString(params))
        //3.设置回调函数
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                cb(JSON.parse(xhr.responseText))
            }
        }
        //4.发送请求
        xhr.send()
    }
    //点击上一页，获取上一页的表情，渲染表情
    document.querySelector('.prev').onclick = function () {
        if (page > 1) {
            ajax('get', `https://yantianfeng.com/api/emotion`, { page: --page, count: 10 }, function (data) {
                var str = data.emotions.map((item, index) => {
                    return `<div><img src="${item.url}"/><div>${item.title}</div></div>`
                }).join('')
                //渲染表情
                document.querySelector('.list').innerHTML = str
            })
        }
    }
    //点击下一页，获取下一页的表情，渲染表情
    document.querySelector('.next').onclick = function () {
        if (page < 4) {
            ajax('get', `https://yantianfeng.com/api/emotion`, { page: ++page, count: 10 }, function (data) {
                var str = data.emotions.map((item, index) => {
                    return `<div><img src="${item.url}"/><div>${item.title}</div></div>`
                }).join('')
                document.querySelector('.list').innerHTML = str
            })

        }
    }

    //ajax('get','https://yantianfeng.com/api/sdfsd');

</script>